<template>
    <div class="main-con editAssociationGoods">
        <!-- 顶部导航 -->
        <div class="breadcrumb-con">
            <el-breadcrumb separator-class="el-icon-arrow-right">
                <el-breadcrumb-item :to="{ path: '/index/associationGoods' }">社群商品</el-breadcrumb-item>
                <el-breadcrumb-item>{{ editText }}社群商品</el-breadcrumb-item>
            </el-breadcrumb>
        </div>

        <!-- 表单信息 -->
        <div class="form-con">
            <!--控制编辑的内容-->
            <div class="top-select-con">
                <el-radio-group v-model="handelType">
                    <el-radio-button label="1">基本信息</el-radio-button>
                    <el-radio-button label="2">商品详情</el-radio-button>
                </el-radio-group>
            </div>
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="110px" class="demo-ruleForm">
                <div class="form-item-con" v-show="handelType == 1">
                    <el-form-item label="商品编号" prop="productNo">
                        <div class="form-item-input">
                            <el-input v-model="ruleForm.productNo" placeholder="请输入商品编号" disabled></el-input>
                        </div>
                    </el-form-item>
                    <el-form-item label="商品名称" prop="newProductName">
                        <div class="form-item-input">
                            <el-autocomplete :disabled="editType == 'update' ? true : false" v-model="ruleForm.newProductName" :fetch-suggestions="querySearch" placeholder="请输入商品名称" value-key="newProductName" :trigger-on-focus="false" @select="handleSelect"></el-autocomplete>
                        </div>
                    </el-form-item>
                    <el-form-item label="商品类别" prop="categoryName">
                        <div class="form-item-input">
                            <el-input v-model="ruleForm.categoryName" placeholder="请输入商品类别" disabled></el-input>
                        </div>
                    </el-form-item>
                    <el-form-item label="社群商品名称" prop="socialProductName">
                        <div class="form-item-input">
                            <el-input v-model="ruleForm.socialProductName" placeholder="请输入社群商品名称"></el-input>
                        </div>
                    </el-form-item>
                    <el-form-item label="副标题">
                        <div class="form-item-input">
                            <el-input v-model="ruleForm.subTitle" placeholder="请输入副标题"></el-input>
                        </div>
                    </el-form-item>
                    <el-form-item label="商品主图" prop="img">
                        <el-upload class="avatar-uploader" action="" :show-file-list="false" :before-upload="uploadProductMainImg"  v-model="ruleForm.img">
                            <img v-if="ruleForm.img" :src="ruleForm.img" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                        <div class="img-tips">*只允许上传1张，建议尺寸 1053*570px，不允许添加视频，允许添加动图</div>
                    </el-form-item>
                    <el-form-item label="商品详情图">
                        <el-upload action="" list-type="picture-card" :file-list="fileList" :before-upload="uploadProductDetialImg" :on-remove="handleRemove">
                            <i class="el-icon-plus"></i>
                        </el-upload>
                        <div class="img-tips">* 最多上传5张，建议尺寸 1125*1089，不允许添加视频，允许添加动图</div>
                    </el-form-item>
                    <el-form-item label="商城售价">
                        <div class="form-item-input">
                            <el-input v-model="ruleForm.mallPrice" placeholder="请输入商城售价"></el-input>
                        </div>
                    </el-form-item>
                    <el-form-item label="成本价">
                        <div class="form-item-input">
                            <el-input v-model="ruleForm.costPrice" placeholder="请输入成本价"></el-input>
                        </div>
                    </el-form-item>
                    <el-form-item label="市场价">
                        <div class="form-item-input">
                            <el-input v-model="ruleForm.marketPrice" placeholder="请输入市场价"></el-input>
                        </div>
                    </el-form-item>
                    <el-form-item label="库存">
                        <div class="form-item-input">
                            <el-input v-model="ruleForm.stock" placeholder="请输入库存"></el-input>
                        </div>
                    </el-form-item>
                    <el-form-item label="限购">
                        <el-checkbox v-model="ruleForm.islimit">限制每人可购买数量</el-checkbox>
						<div style="display: flex;align-items: center;" v-if="ruleForm.islimit">
							<div>
								每一个买家账号每个活动限购
							</div>
							<div style="width: 60px;margin: 0 10px;">
								<el-input v-model="ruleForm.limitCount" @blur="checkLimitCount"></el-input>
							</div>
							<div>
								件
							</div>
						</div>
                    </el-form-item>
                    <el-form-item label="商城状态">
                        <div class="form-item-input">
                            <el-radio-group v-model="ruleForm.status">
                                <el-radio :label="1">上架</el-radio>
                                <el-radio :label="0">下架</el-radio>
                            </el-radio-group>
                        </div>
                    </el-form-item>
                    <el-form-item label="分享标题">
                        <div class="form-item-input">
                            <el-input v-model="ruleForm.shareTitle" placeholder="请输入分享标题"></el-input>
                        </div>
                    </el-form-item>
                    <el-form-item label="分享图片">
                        <el-upload class="avatar-uploader" action="" :show-file-list="false" :before-upload="uploadShareImg">
                            <img v-if="ruleForm.shareImg" :src="ruleForm.shareImg" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                        <div class="img-tips">*只允许上传1张，建议尺寸 1053*570px，不允许添加视频，允许添加动图</div>
                    </el-form-item>
                </div>
                <div class="form-item-con form-item-um-con" v-show="handelType == 2">
                    <el-form-item label="商品详情：" class="mt20">
                        <div class="ueditor">
                            <UM :config="config" :id="um1" ref="um" :defaultMsg="ruleForm.content"></UM>
                        </div>
                    </el-form-item>
                </div>
                <el-form-item>
                    <div class="submit-btn-con">
                        <el-button type="primary" @click="submitForm('ruleForm')">确定</el-button>
                        <el-button @click="handleBack">取消</el-button>
                    </div>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script>
import UM from '@/components/m-ueditor/m-ueditor.vue'
import { findGoodsInfoByGoodsName, addAssociationGoods, updateAssociationGoods } from '@/common/service/productManagement/associationGoods.js'
import { getUploadImgSrc } from '@/common/service/uploadImg/uploadImg.js'
export default {
    name: "editAssociationGoods",
    data(){
        return {
            handelType: 1, //控制编辑的内容 1--基本信息  2--商品详情
            //表单信息
            ruleForm: {
                productNo: '', //商品编号
                productName: '', //商品名称
                newProductName: '',
                categoryName: '', //商品类别
                categoryId: '', //商品类别ID
                socialProductName: '', //社群商品名称
                subTitle: '', //副标题
                img: '', //商品主图
                mallPrice: '', //商城售价
                costPrice: '', //成本价
                marketPrice: '', //市场价
                stock: '', //库存
                islimit: false, //是否限购
                limitCount: '0', //限购数量
                status: 1, //商城状态
                shareTitle: '', //分享标题
                shareImg: '', //分享图片
                content: '' //商品详情信息
            },
            rules: {
                productNo: [{
                    required: true,
                    message: '请输入商品编号',
                    trigger: 'change'
                }],
                newProductName: [{
                    required: true,
                    message: '请选择商品名称',
                    trigger: 'change'
                }],
                categoryName: [{
                    required: true,
                    message: '请选择商品类别',
                    trigger: 'change'
                }, ],
                socialProductName: [{
                    required: true,
                    message: '请输入社群商品名称',
                    trigger: 'change'
                }],
                img: [{
                    required: true,
                    message: '请选择商品主图',
                    trigger: 'change'
                }]
            },
            //商品详情图片
            fileList: [],

            /*富文本编辑器*/
            um1: "um1", // 不同编辑器必须不同的id
            config: {
                initialFrameWidth: null,
                initialFrameHeight: 500,
                autoHeightEnabled: false,
                toolbar: [
                    'undo redo | paragraph bold italic underline strikethrough | superscript subscript | forecolor backcolor | removeformat |',
                    'selectall cleardoc',
                    '| justifyleft justifycenter justifyright justifyjustify |',
                    'addUploadImg addUploadVideo',
                    '| '
                ]
            }
        }
    },
    created() {
        this.editType = this.$route.query.editType;
        this.editText = this.$route.query.editText;
        if (this.editType == "update") {
            this.editId = this.$route.query.editId;
            this.editData = JSON.parse(localStorage.getItem('editData'));
            this.ruleForm.id = this.editData.id;
            this.ruleForm.accountNo = this.editData.accountNo;
            this.ruleForm.userName = this.editData.userName;
            this.ruleForm.password = this.editData.password;
            this.ruleForm.telPhone = this.editData.telPhone;
            this.ruleForm.role = this.editData.role;
            this.ruleForm.email = this.editData.email;
        }
    },
    beforeDestroy(){
        //清除本地缓存的编辑数据
        localStorage.removeItem("editData");
    },
    methods: {
        /*-------------------------------------模糊查询商品信息-------------------------------------*/
        /*商品名称模糊匹配*/
        querySearch(queryString, cb) {
            findGoodsInfoByGoodsName({
                productName: this.ruleForm.newProductName,
                pageSize: 1000
            }).then((res) => {
                res.content.forEach((item, index) => {
                    item.newProductName = item.productNo + item.productName;
                })
                cb(res.content);
            }).catch((res) => {
                this.$message({
                    type: 'error',
                    message: res.message
                })
            })
        },
        handleSelect(item) {
            this.selectFlag = true;
            this.ruleForm.productNo = item.productNo
            this.ruleForm.productName = item.productName
            this.ruleForm.categoryName = item.bigCategoryName
            this.ruleForm.categoryId = item.bigCategoryId
            this.ruleForm.socialProductName = item.productName
        },
        /*-------------------------------------图片上传操作-------------------------------------*/
        //上传商品主图
        uploadProductMainImg(file) {
            const self = this;
            let fileType = file.type; //==='image/jpeg';
            let typeList = ['image/jpg', 'image/png', 'image/jpeg']

            if(typeList.indexOf(fileType) == -1) {
                this.$message.error('上传图片只能是 JPG、PNG格式!');
                return false;
            }
            getUploadImgSrc(file).then((res) => {
                self.ruleForm.img = res;
            }).catch((res) => {
                this.$message.error('上传失败');
            })
            return false;
        },
        //上传分享图片
        uploadShareImg(file) {
            const self = this;
            let fileType = file.type; //==='image/jpeg';
            let typeList = ['image/jpg', 'image/png', 'image/jpeg']

            if(typeList.indexOf(fileType) == -1) {
                this.$message.error('上传图片只能是 JPG、PNG格式!');
                return false;
            }
            getUploadImgSrc(file).then((res) => {
                self.ruleForm.shareImg = res;
            }).catch((res) => {
                this.$message.error('上传失败');
            })
            return false;
        },
        //上传商品详情图
        uploadProductDetialImg(file) {
            let fileType = file.type; //==='image/jpeg';
            let typeList = ['image/jpg', 'image/png', 'image/jpeg']

            if(typeList.indexOf(fileType) == -1) {
                this.$message.error('上传图片只能是 JPG、PNG格式!');
                return false;
            }
            if(this.fileList.length >= 5) {
                this.$message.error('最多上传5张！');
                return false;
            }
            getUploadImgSrc(file).then((res) => {
                this.fileList.push({
                    name: res,
                    url: res
                });
            }).catch((res) => {
                this.$message.error('上传失败');
            })
            return false;
        },
        //删除商品详情图
        handleRemove(file, fileList) {
            this.fileList = fileList;
        },
        /*-------------------------------------添加操作-------------------------------------*/
        //执行添加操作
        _addAssociationGoods() {
            this.UMkeydown();
            //判断是否限购
            if(this.ruleForm.islimit == false) {
                this.ruleForm.limitCount = '0'
            }
            //商品详情图数据处理
            var imgArr = [];
            this.fileList.forEach((item, index) => {
                imgArr.push(item.url);
            })
            var imgStr = imgArr.join(",");

            var data = {
                productNo: this.ruleForm.productNo, //商品编号
                productName: this.ruleForm.productName, //商品名称
                categoryName: this.ruleForm.categoryName, //商品类别
                categoryId: this.ruleForm.categoryId, //商品类别ID
                socialProductName: this.ruleForm.socialProductName, //社群商品名称
                subTitle: this.ruleForm.subTitle, //副标题
                img: this.ruleForm.img, //商品主图	
                imgs: imgStr, //商品详情图
                mallPrice: this.ruleForm.mallPrice, //商城售价
                costPrice: this.ruleForm.costPrice, //成本价
                marketPrice: this.ruleForm.marketPrice, //市场价
                stock: this.ruleForm.stock, //库存
                limitCount: this.ruleForm.limitCount, //限购数量
                status: this.ruleForm.status, //商城状态
                shareTitle: this.ruleForm.shareTitle, //分享标题
                shareImg: this.ruleForm.shareImg, //分享图片
                detail: this.ruleForm.content //商品详情信息
            }

            console.log(data)
            // addAssociationGoods(data).then(res => {
            //     console.log(res);
            //     this.$message({
            //         message: '添加成功',
            //         type: 'success',
            //         duration: 1000,
            //     });
            //     this.handleBack();
            // }).catch(err => {
            //     this.$message.error(err.message);
            // })
        },
        /*-------------------------------------编辑操作-------------------------------------*/
        //执行修改操作
        _updateAssociationGoods() {
            if(this.form.islimit == false) {
                this.form.limitCount = '0'
            }
            var imgArr = [];
            this.fileList.forEach((item, index) => {
                imgArr.push(item.url);
            })
            var imgStr = imgArr.join(",");
            var data = {
                id: this.form.id,
                productNo: this.form.productNo, //商品编号
                productName: this.form.productName, //商品名称
                categoryName: this.form.categoryName, //商品类别
                categoryId: this.form.categoryId, //商品类别ID
                socialProductName: this.form.socialProductName, //社群商品名称
                subTitle: this.form.subTitle, //副标题
                img: this.form.img, //商品主图	
                imgs: imgStr, //商品详情图
                mallPrice: this.form.mallPrice, //商城售价
                costPrice: this.form.costPrice, //成本价
                marketPrice: this.form.marketPrice, //市场价
                stock: this.form.stock, //库存
                limitCount: this.form.limitCount, //限购数量
                status: this.form.status, //商城状态
                shareTitle: this.form.shareTitle, //分享标题
                shareImg: this.form.shareImg, //分享图片
                detail: this.content //商品详情信息
            }
            updateAssociationGoods(data).then(res => {
                this.$message({
                    message: '修改成功',
                    type: 'success',
                    duration: 1000,
                });
                this.handleBack();
            }).catch(err => {
                this.$message.error(err.message);
            })
        },
        /*-------------------------------------保存操作-------------------------------------*/
        submitForm(formName){
            this.$refs[formName].validate((valid) => {
                if(valid) {
                    if(this.fileList.length) {
                        if(this.ruleForm.islimit == true){  //有限购
                            if(this.ruleForm.limitCount == '') {
                                this.$message.error('限购数量不能为空');
                            } else if(this.ruleForm.limitCount == '0') {
                                this.$message.error('限购数量不能为0');
                            } else if(/[^\d^\.]+/g.test(this.ruleForm.limitCount)){
                                this.$message.error('限购数量只能输入数字类型的值');
                            }else{
                                if(this.editType == 'add') {
                                    this._addAssociationGoods();
                                } else if(this.editType == 'update') {
                                    this._updateAssociationGoods();
                                }
                            }
                        }else{  //无限购
                            if(this.editType == 'add') {
                                this._addAssociationGoods();
                            } else if(this.editType == 'update') {
                                this._updateAssociationGoods();
                            }
                        }
                    } else {
                        this.$message.error("商品详情图片不能为空");
                    }

                } else {
                    return false;
                }
            });
        },

        /*-------------------------------------返回操作-------------------------------------*/
        handleBack() {
            this.$router.push({
                path: '/index/associationGoods',
            });
        },

        /*-------------------------------------富文本操作-------------------------------------*/
        UMkeydown() {
            this.ruleForm.content = this.$refs.um.getUMContent();
        },
        hasContents() {
            return this.$refs.um.hasContents();
        },
        setContent(info) {
            this.$refs.um.setContents(false, info);
        },
        setcontent(val) {
            this.ruleForm.content = val;
            this.setContent(val);
        }
    },
    components: {
        UM
    },
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
    
</style>